package com.zzsy.carosshopprojects.activitys.home.mainpage.member.memberconsum.order;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.king.base.util.ToastUtils;
import com.yzy.voice.VoicePlay;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.payresult.PayResultAc;
import com.zzsy.carosshopprojects.base.BaseViewMode;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.ActivityBean;
import com.zzsy.carosshopprojects.bean.ActivityResultBean;
import com.zzsy.carosshopprojects.bean.BaseBean;
import com.zzsy.carosshopprojects.bean.ConponYesList;
import com.zzsy.carosshopprojects.bean.CouponChoseBean;
import com.zzsy.carosshopprojects.bean.CreateOrderBean;
import com.zzsy.carosshopprojects.bean.RedPageBean;
import com.zzsy.carosshopprojects.bean.RedPageResultBean;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.AlgorithmUtil;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.md5.Md5Util;
import com.zzsy.carosshopprojects.view.paypassdialog.PayPassDialog;
import com.zzsy.carosshopprojects.view.paypassdialog.PayPassView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.lifecycle.MutableLiveData;

public class OrderDetailMode extends BaseViewMode {
    List<RedPageBean> storidList = new ArrayList<>();
    List<RedPageBean> couponList = new ArrayList<>();
    private ArrayList<ActivityBean> activityList = new ArrayList<>();
    private String activityId = "";
    private String activityPositionId = "";
    private String couponIdsReceive = "";
    private String serviceCardIds = "";
    private int rebateAmount = 0;
    private String rebate = "";
    private int downAmount = 0;
    private String nowOilsPrice = "";
    private String fullReductionAmount = "0";
    //活动是的优惠
    private int activityPreMoney = 0;
    private int preMoney = 0;
    private String oilPrice = "";
    private String isUseCoupon = "";
    private String memberCardId = "";
    private String memberId = "";
    private String productId = "";
    private String productInfoId = "";
    private String orderAmount = "";
    private String activitySuperposition = "";
    private String oilNum = "";
    private String paySwitch = "";
    private String parentId = "";
    private PayPassDialog payPassDialog;
    /**
     * 创建两个集合 判断是否可以叠加 然后排序
     */
    List<ConponYesList> conponYesListList = new ArrayList<>();
    private String couponIds = "";
    private MutableLiveData<RedPageResultBean> liveDataRedPage;//优惠券红包
    private MutableLiveData<ActivityResultBean> liveDataActivity;//活动
    private MutableLiveData<String> liveActualPayment;//实际支付

    private ActivityResultBean activityResultBean = new ActivityResultBean();//全局的活动结果
    private RedPageResultBean redPageResultBean = new RedPageResultBean();//全局的优惠券结果

    public MutableLiveData<ActivityResultBean> getLiveDataActivity() {
        if (liveDataActivity == null)
            liveDataActivity = new MutableLiveData<>();
        return liveDataActivity;
    }

    public MutableLiveData<RedPageResultBean> getliveDataRedPage() {
        if (liveDataRedPage == null)
            liveDataRedPage = new MutableLiveData<>();
        return liveDataRedPage;
    }

    public MutableLiveData<String> getliveActualPayment() {
        if (liveActualPayment == null)
            liveActualPayment = new MutableLiveData<>();
        return liveActualPayment;
    }

    /**
     * 初始化数据
     */
    public void setData(String oilPrice, String isUseCoupon, String memberCardId, String memberId, String productId, String productInfoId, String orderAmount, String oilNum, String paySwitch, String parentId) {
        this.oilPrice = oilPrice;
        this.isUseCoupon = isUseCoupon;
        this.memberCardId = memberCardId;
        this.memberId = memberId;
        this.productId = productId;
        this.productInfoId = productInfoId;
        this.orderAmount = orderAmount;
        this.oilNum = oilNum;
        this.paySwitch = paySwitch;
        this.parentId = parentId;
    }

    /**
     * 活动结果发射给页面
     */
    private void sendActivityData() {
        liveDataActivity.postValue(activityResultBean);
    }

    /**
     * 红包卡券结果发射给页面
     */
    private void sendRedPageData() {
        liveDataRedPage.postValue(redPageResultBean);
    }

    /**
     * 获取活动折扣
     *
     * @param context
     */
    public void getActivityList(Activity context, Map<String, String> map) {
        Log.d("xxxx", isUseCoupon + "/");
        RequestUtils.GetActivity(context, map, new MyObserver<List<ActivityBean>>(context) {
            @Override
            public void onSuccess(List<ActivityBean> result) {
                activityList.clear();
                if (result != null && result.size() > 0) {
                    //计算出实付金额
                    activitySuperposition = result.get(0).getSuperposition();
                    if (!StringUtils.isEmpty(activitySuperposition)) {
                        activityList.addAll(result);
                        setPayAmount(result.get(0), activitySuperposition, context);
                        Log.d("xxxx", "1111111");
                    } else {
                        ToastUtils.showToast(context.getApplicationContext(), "叠加活动数据异常！");
                        context.finish();
                    }

                } else {
                    //如果没有活动  直接用订单金额
                    if ("0".equals(isUseCoupon)) {
                        Log.d("xxxx", "2222222");
                        //如果没有活动  直接用订单金额
                        getCouponList(context, orderAmount, "2");
                    }

                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {

                switch (code) {
                    case 404:
                        if ("0".equals(isUseCoupon)) {
                            //如果没有活动  直接用订单金额
                            getCouponList(context, orderAmount, "2");
                        }
                        break;
                    case 500:
                        activityResultBean.setStateMsg("活动异常，暂时无法使用活动!");
                        //如果没有活动  直接用订单金额
                        if ("0".equals(isUseCoupon)) {
                            //如果没有活动  直接用订单金额
                            getCouponList(context, orderAmount, "2");
                        }
                        break;
                    default:
                        ToastUtils.showToast(context.getApplicationContext(), errorMsg);
                        context.finish();
                        break;
                }

            }
        });

    }

    /**
     * 获取优惠券列表 进行最优筛选
     */
    private void getCouponList(Context context, String shifuAmount, String activitySuperposition) {

        RequestUtils.MemberRedPackedList(context, DataUtil.getInstance().getStoreId(), memberId, productId, memberCardId, new MyObserver<List<RedPageBean>>(context, false) {
            @Override
            public void onSuccess(List<RedPageBean> result) {
                Log.d("xxxx", "3333333333");
                if (result != null && result.size() > 0) {
                    storidList.clear();
                    couponList.clear();
                    for (int i = 0; i < result.size(); i++) {
                        if (result.get(i) != null) {
                            String couponKind = result.get(i).getCouponKind();
                            String useActivity = result.get(i).getUseActivity();
                            if (!StringUtils.isEmpty(couponKind) && !StringUtils.isEmpty(useActivity) && "2".equals(couponKind) && useActivity.equals("1")) {
                                storidList.add(result.get(i));
                            }
                            couponList.add(result.get(i));
                        }
                    }
                    setDataListConPon(storidList, shifuAmount, result.size(), activitySuperposition);
                } else {
                    preMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(shifuAmount)).intValue();
                    setXiaUI();
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                Log.d("xxxx", "444444");
                preMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(shifuAmount)).intValue();
                setXiaUI();
                ToastUtils.showToast(context.getApplicationContext(), errorMsg);
            }
        });
    }

    /**
     * 将数据进行筛选
     */
    private void setDataListConPon(List<RedPageBean> list, String shifuAmount, int size, String activitySuperposition) {
        conponYesListList.clear();
        for (int i = 0; i < list.size(); i++) {
            ConponYesList conponYesList = new ConponYesList();
            if ((list.get(i).getMinimumAmount() <= Double.valueOf(orderAmount))
                    && (list.get(i).getPayType().contains("4"))
            ) {
                conponYesList.setCouponName(list.get(i).getCouponName());
                conponYesList.setEndTime(list.get(i).getTimeOut());
                conponYesList.setFullAmount(list.get(i).getMinimumAmount());
                conponYesList.setPreAmount(list.get(i).getPreAmount());
                conponYesList.setId(list.get(i).getId());
                conponYesList.setPreType(list.get(i).getPreType());
                conponYesList.setSuperposition(list.get(i).getSuperposition());
                conponYesList.setGrantSource(list.get(i).getGrantSource());
                conponYesListList.add(conponYesList);

            }
        }
        /**
         * 将两个集合进行排序
         * */
        SortList(conponYesListList, shifuAmount, size, activitySuperposition);
    }

    private void SortList(List<ConponYesList> conponYesListList, String shifuAmount, int size, String activitySuperposition) {
        Collections.sort(conponYesListList, new PriceComparator()); // 根据价格排序
        boolean isHave = false;
        if (conponYesListList.size() == 0) {
            if (size > 0) {
                if (couponList != null && couponList.size() > 0) {
                    for (int i = 0; i < couponList.size(); i++) {
                        if (couponList.get(i) != null && !StringUtils.isEmpty(couponList.get(i).getPayType())) {
                            String payType = couponList.get(i).getPayType();
                            String[] payTypeArray = payType.split(",");
                            if (payTypeArray != null && payTypeArray.length > 0) {
                                List<String> payTypeList = new ArrayList<String>();
                                for (int j = 0; j < payTypeArray.length; j++) {
                                    String payTypeObj = payTypeArray[j];
                                    if (!StringUtils.isEmpty(payTypeObj)) {
                                        payTypeList.add(payTypeObj);
                                    }
                                }
                                if ((couponList.get(i).getMinimumAmount() <= Double.valueOf(orderAmount)) && (payTypeList.contains("4"))) {
                                    isHave = true;
                                }
                            }
                        }
                    }
                }
                if (isHave) {
                    redPageResultBean.setCouponMsg("有优惠券可用！");
                    redPageResultBean.setCpounNum(0);
                    sendRedPageData();
                } else {
                    redPageResultBean.setCouponMsg("暂无优惠券可用！");
                    sendRedPageData();
                }
                preMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(shifuAmount)).intValue();
                setXiaUI();
            } else {
                redPageResultBean.setCouponMsg("暂无优惠券可用！");
                sendRedPageData();
                preMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(shifuAmount)).intValue();
                setXiaUI();
            }

        } else {
            /**
             * 判断能否与活动叠加使用
             * */
            if (!StringUtils.isEmpty(activitySuperposition)) {

                if ("1".equals(activitySuperposition)) {
                    //设置可与活动叠加
                    setDieCoupon(shifuAmount);
                } else if ("0".equals(activitySuperposition)) {
                    //设置不可与活动叠加使用
                    int index = 0;
                    for (int i = 0; i < storidList.size(); i++) {
                        if ((storidList.get(i).getMinimumAmount() <= Double.valueOf(orderAmount))
                                && (storidList.get(i).getPayType().contains("4"))
                        ) {
                            index++;
                        }
                    }
                    setNoDieCoupon("有优惠券可用！", shifuAmount);
                } else {
                    //设置可与活动叠加
                    setDieCoupon(shifuAmount);
                }
            }
        }
    }

    /**
     * 设置可与活动叠加使用
     */
    private void setDieCoupon(String shifuAmount) {
        /**
         * 将优惠券选中的id进行字符串拼接
         * */
        String idListStr = "";
        /**
         * 优惠额度
         * */
        int preAmountInt = 0;
        /**
         * 满减额度
         * */
        int fullAmount = 0;
        int index = 0;

        //剩余额度
        double syAmount = 0;
        for (int i = 0; i < conponYesListList.size(); i++) {
            syAmount = Double.valueOf(orderAmount) - Double.valueOf(fullAmount);
            if (syAmount >= conponYesListList.get(i).getFullAmount()) {
                ConponYesList myLive = conponYesListList.get(i);
                idListStr = idListStr + "," + myLive.getId();
                preAmountInt = preAmountInt + myLive.getPreAmount();
                fullAmount += myLive.getFullAmount();
                index++;

            }
        }
        if (!StringUtils.isEmpty(idListStr)) {
            couponIds = idListStr.substring(1, idListStr.length());
            BigDecimal bigDecimal = ConverterHelper.toBigDecimal(preAmountInt).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            double preAmountDou = bigDecimal.doubleValue();
            redPageResultBean.setCouponMsg("优惠了" + preAmountDou + "元");
            redPageResultBean.setRealPay(AlgorithmUtil.getSubtractAmount(orderAmount, preAmountDou + ""));
            redPageResultBean.setCpounNum(index);
            redPageResultBean.setCpounContent("已选" + index + "张优惠券");
            sendRedPageData();
        }
        int activityPreMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(shifuAmount)).intValue();
        preMoney = ConverterHelper.toBigDecimal(preAmountInt).add(ConverterHelper.toBigDecimal(activityPreMoney)).intValue();
        setXiaUI();
    }

    private void setNoDieCoupon(String couponName, String shifuAmount) {
        couponIds = "";
        RedPageResultBean redPageResultBean = new RedPageResultBean();
        redPageResultBean.setCouponMsg(couponName);
        redPageResultBean.setHaveCoupon(true);
        liveDataRedPage.postValue(redPageResultBean);
        preMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(shifuAmount)).intValue();
        setXiaUI();
    }

    /**
     * 计算出实付金额 然后进行优惠券选择 得出最终实付金额
     */
    public void setPayAmount(ActivityBean data, String activitySuperposition, Activity context) {
        this.activitySuperposition = activitySuperposition;
        String activityKind = data.getActivityKind();//1 是折扣 2 是减额
        String activityName = data.getActivitySummary();
        String activityValue = data.getActivityValue();
        activityId = data.getActivityId();
        activityPositionId = data.getActivityPositionId();
        //清除上次赋值
        couponIdsReceive = "";
        serviceCardIds = "";
        rebateAmount = 0;
        rebate = "";
        downAmount = 0;
        nowOilsPrice = "";
        fullReductionAmount = "0";
        activityPreMoney = 0;
        preMoney = 0;

        if (StringUtils.isEmpty(activityKind)) {
            activityKind = "";
        }
        if (StringUtils.isEmpty(activityValue)) {
            activityValue = "";
        }
        if (StringUtils.isEmpty(activityName)) {
            activityName = "";
        }

        activityResultBean.setStateMsg(activityName);
        sendActivityData();

        if (!StringUtils.isEmpty(activityKind) && !StringUtils.isEmpty(activityValue)) {
            if ("1".equals(activityKind)) {
                String rebateValue = data.getRebateValue();
                String rebateLimit = data.getRebateLimit();

                if (!StringUtils.isEmpty(rebateValue) && !StringUtils.isEmpty(rebateLimit)) {

                    if ("0".equals(rebateLimit)) {

                        String rebateAmounts = ConverterHelper.toBigDecimal(rebateValue).divide(ConverterHelper.toBigDecimal(10)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        //打折后的订单金额
                        String rebateOrderNumberAmount = ConverterHelper.toBigDecimal(orderAmount).multiply(ConverterHelper.toBigDecimal(rebateAmounts)).toString();
                        preMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(rebateOrderNumberAmount)).intValue();
                        nowOilsPrice = ConverterHelper.toBigDecimal(oilPrice).multiply(ConverterHelper.toBigDecimal(rebateAmounts)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
                        rebateAmount = preMoney;
                        activityPreMoney = preMoney;
                        //计算会员价
                        nowOilsPrice = ConverterHelper.toBigDecimal(oilPrice).multiply(ConverterHelper.toBigDecimal(rebateAmounts)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();

                    } else {
                        int rebateLimitAmount = ConverterHelper.toBigDecimal(rebateLimit).multiply(ConverterHelper.toBigDecimal(100)).intValue();
                        String rebateAmounts = ConverterHelper.toBigDecimal(rebateValue).divide(ConverterHelper.toBigDecimal(10)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                        //打折后的订单金额
                        String rebateOrderNumberAmount = ConverterHelper.toBigDecimal(rebateLimitAmount).multiply(ConverterHelper.toBigDecimal(rebateAmounts)).toString();
                        int preMoneyRebate = ConverterHelper.toBigDecimal(rebateLimitAmount).subtract(ConverterHelper.toBigDecimal(rebateOrderNumberAmount)).intValue();
                        rebateAmount = preMoneyRebate;

                        if (!StringUtils.isEmpty(activityValue) && !StringUtils.isEmpty(oilPrice)) {

                            //获取直降金额
                            int activityAmount = ConverterHelper.toBigDecimal(activityValue).multiply(ConverterHelper.toBigDecimal(100)).intValue();
                            //获取可以直降的金额
                            String downMoney = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(rebateLimitAmount)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
                            //直降的优惠金额
                            downAmount = ConverterHelper.toBigDecimal(downMoney).divide(ConverterHelper.toBigDecimal(oilPrice), 2, BigDecimal.ROUND_HALF_UP).multiply(ConverterHelper.toBigDecimal(activityAmount)).intValue();
                            preMoney = ConverterHelper.toBigDecimal(preMoneyRebate).add(ConverterHelper.toBigDecimal(downAmount)).intValue();
                            activityPreMoney = preMoney;

                        } else {
                            ToastUtils.showToast(context.getApplicationContext(), "活动数据异常1！");
                        }
                        Log.d("xxxx", orderAmount + "/" + oilPrice);
                        //获取加油升数
                        String rise = ConverterHelper.toBigDecimal(orderAmount).divide(ConverterHelper.toBigDecimal(oilPrice), 3, BigDecimal.ROUND_HALF_UP).doubleValue() + "";
                        //获取实付金额
                        int shifuAmount = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(preMoney)).intValue();
                        //当前油价

                        nowOilsPrice = ConverterHelper.toBigDecimal(shifuAmount).divide(ConverterHelper.toBigDecimal(rise), 2, BigDecimal.ROUND_HALF_UP).toString();

                    }

                } else {
                    ToastUtils.showToast(context.getApplicationContext(), "活动数据异常3！");
                    context.finish();
                }
            } else if ("9".equals(activityKind)) {
                if (!StringUtils.isEmpty(activityValue) && !StringUtils.isEmpty(oilPrice)) {
                    nowOilsPrice = ConverterHelper.toBigDecimal(oilPrice).subtract(ConverterHelper.toBigDecimal(activityValue)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
                    downAmount = ConverterHelper.toBigDecimal(orderAmount).divide(ConverterHelper.toBigDecimal(oilPrice), 2, BigDecimal.ROUND_HALF_UP).multiply(ConverterHelper.toBigDecimal(activityValue)).intValue();
                    preMoney = downAmount;
                    activityPreMoney = preMoney;
                    setDataIds(data);

                } else {
                    ToastUtils.showToast(context.getApplicationContext(), "活动数据异常2！");
                    context.finish();
                }
            }
        } else {
            preMoney = 0;
            activityPreMoney = 0;
        }
        if (!StringUtils.isEmpty(activityKind) && "4".equals(activityKind)) {
            setDataIds(data);
        }
        if ("0".equals(isUseCoupon)) {
            int shifuAmount = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(preMoney)).intValue();
            getCouponList(context, shifuAmount + "", activitySuperposition);
        } else {
            setXiaUI();
        }

    }

    /**
     * 设置折后UI
     */
    private void setXiaUI() {
        BigDecimal bigDecimal = ConverterHelper.toBigDecimal(orderAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal bigDecima2 = ConverterHelper.toBigDecimal(preMoney).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        double amounts = bigDecimal.doubleValue();
        double preMoneys = bigDecima2.doubleValue();
        double yfMounts = ConverterHelper.toBigDecimal(amounts).subtract(ConverterHelper.toBigDecimal(preMoneys)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (yfMounts <= 0) {
            yfMounts = 0;
        }
        liveActualPayment.postValue("￥" + yfMounts);
    }


    /**
     * 获取优惠券和服务卡ID
     */
    private void setDataIds(ActivityBean data) {
        if (data.getCouponList() != null && data.getCouponList().size() != 0) {
            for (int i = 0; i < data.getCouponList().size(); i++) {
                couponIdsReceive += "," + String.valueOf(data.getCouponList().get(i).getId());
            }
        }
        if (data.getServiceCardDTOList() != null && data.getServiceCardDTOList().size() != 0) {
            for (int i = 0; i < data.getServiceCardDTOList().size(); i++) {
                serviceCardIds += "," + String.valueOf(data.getServiceCardDTOList().get(i).getId());
            }
        }
    }

    /**
     * 不使用活动
     */
    public void noUseActivty(Context context) {
        preMoney = 0;
        couponIdsReceive = "";
        serviceCardIds = "";
        rebateAmount = 0;
        rebate = "";
        downAmount = 0;
        nowOilsPrice = "";
        preMoney = 0;
        activityPreMoney = 0;
        if (activityList != null && activityList.size() > 0) {
            activityResultBean.setStateMsg("有活动可选!");

        } else {
            activityResultBean.setStateMsg("暂无活动!");
        }
        sendActivityData();
        if ("0".equals(isUseCoupon)) {
            //如果没有活动  直接用订单金额
            getCouponList(context, orderAmount, "2");

        } else if ("1".equals(isUseCoupon)) {
            setXiaUI();
        }

    }

    /**
     * 选择优惠券的处理结果
     */
    public void selectCoupon(CouponChoseBean couponChoseBean) {
        boolean isHaves = false;
        if (couponChoseBean.getPreAmountInt() == -1 && couponChoseBean.getSuperposition() == -1 && StringUtils.isEmpty(couponChoseBean.getIds())) {
            if (couponList != null && couponList.size() > 0) {
                for (int i = 0; i < couponList.size(); i++) {
                    if ((Integer.valueOf(orderAmount) >= couponList.get(i).getMinimumAmount())
                            && (couponList.get(i).getPayType().contains("4"))
                    ) {
                        isHaves = true;
                    }
                }
            }

            if (isHaves) {
                redPageResultBean.setCouponMsg("有优惠券可用！");
                redPageResultBean.setCpounNum(0);
            } else {
                redPageResultBean.setCouponMsg("暂无优惠券可用！");
                redPageResultBean.setCpounNum(0);
            }

            if (StringUtils.isEmpty(activityId) || activityId.equals("0")) {
                // 清空活动
                clearActivity();
            }
            preMoney = activityPreMoney;
            couponIds = "";
            sendRedPageData();
            setXiaUI();
        } else {
            couponIds = String.valueOf(couponChoseBean.getIds());
            String isUse = couponChoseBean.getIsUse();
            if (!StringUtils.isEmpty(isUse)) {
                String[] storeIdArray = isUse.split(",");
                List<String> storeIdList = Arrays.asList(storeIdArray);
                boolean b;
                if (storeIdList.contains("0")) {
                    b = false;
                } else if (storeIdList.contains("1")) {
                    b = true;
                } else {
                    b = false;
                }
                getYesCoupon(b, couponChoseBean.getPreAmountInt(), couponChoseBean.getIndex(), activitySuperposition);
            }
        }

    }

    private void getYesCoupon(boolean isUse, int preAmount, int size, String activitySuperposition) {
        boolean isSh = false;
        if (isUse) {
            if ("0".equals(activitySuperposition)) {
                //清除上次赋值
                couponIdsReceive = "";
                serviceCardIds = "";
                rebateAmount = 0;
                rebate = "";
                downAmount = 0;
                nowOilsPrice = "";
                isSh = true;
                // 清空活动
                clearActivity();
            }
            preMoney = ConverterHelper.toBigDecimal(preAmount).add(ConverterHelper.toBigDecimal(activityPreMoney)).intValue();

            double preMoneys = ConverterHelper.toBigDecimal(preAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            redPageResultBean.setCouponMsg("优惠了" + preMoneys + "元");
            redPageResultBean.setRealPay(AlgorithmUtil.getSubtractAmount(orderAmount, preMoneys + ""));
            redPageResultBean.setCpounNum(size);
            redPageResultBean.setCpounContent("已选" + size + "张优惠券");
            sendRedPageData();

            if (activityList != null && activityList.size() > 0) {
                if (StringUtils.isEmpty(activityResultBean.getStateMsg())) {
                    if (isSh) {
                        activityResultBean.setStateMsg("有活动可选!");
                    } else {
                        activityResultBean.setStateMsg("暂无活动!");
                        activityResultBean.setStateMsg("");
                    }

                }
            } else {
                activityResultBean.setStateMsg("暂无活动!");
            }

            sendActivityData();


        } else {
            //清除上次赋值
            couponIdsReceive = "";
            serviceCardIds = "";
            rebateAmount = 0;
            rebate = "";
            downAmount = 0;
            nowOilsPrice = "";
            // 清空活动
            clearActivity();
            preMoney = ConverterHelper.toBigDecimal(preAmount).intValue();
            redPageResultBean.setCpounContent("已选" + size + "张优惠券");
            redPageResultBean.setCpounNum(size);
            double preMoneys = ConverterHelper.toBigDecimal(preAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            redPageResultBean.setCouponMsg("优惠了" + preMoneys + "元");
            sendRedPageData();
            //  activityResultBean.setStateMsg("有活动可选!");
            // sendActivityData();
            if (activityList != null && activityList.size() > 0) {
                activityResultBean.setStateMsg("有活动可选!");
            } else {
                activityResultBean.setStateMsg("暂无活动!");
            }
            sendActivityData();
        }
        setXiaUI();
    }

    /**
     * 清除活动创建订单的数据
     */
    public void clearActivity() {
        activityId = "";
        activityPositionId = "";
        activityPreMoney = 0;
        activitySuperposition = "0";
        activityResultBean.setStateMsg("");
    }

    /**
     * 收款
     */
    public void toPay(Activity context, String balance, String realPay) {
        int payAmount = ConverterHelper.toBigDecimal(orderAmount).subtract(ConverterHelper.toBigDecimal(preMoney)).intValue();
        if (payAmount < 0) {
            payAmount = 0;
            preMoney = Integer.valueOf(orderAmount);
        }
        if (realPay.length() > 0) {
            String payMent = AlgorithmUtil.getMultiplyAmount(realPay.substring(1, realPay.length()));
            balance = AlgorithmUtil.getMultiplyAmount(balance);
            if (Double.valueOf(balance) < Double.valueOf(payMent)) {
                ToastUtils.showToast(context.getApplicationContext(), "余额不足");
            } else {
                getToken(context, token -> {
                    getTokens(context, token, payMent);
                });
            }

        } else {
            ToastUtils.showToast(context.getApplicationContext(), "实付款金额有误！");
        }

    }


    /**
     * 获取Token
     *
     * @param context
     */
    public void getTokens(Activity context, String tokenMsg, String payMent) {
        BigDecimal bigDecimals = ConverterHelper.toBigDecimal(orderAmount).divide(ConverterHelper.toBigDecimal(oilPrice), 2, BigDecimal.ROUND_HALF_UP);
        String rise = bigDecimals.toString();
        nowOilsPrice = ConverterHelper.toBigDecimal(StringUtils.isEmpty(nowOilsPrice) ? oilPrice : nowOilsPrice).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
        Map<String, String> map = new HashMap<>();
        map.put("idempotenceToken", tokenMsg);
        map.put("activityId", activityId);
        map.put("activityPositionId", activityPositionId);
        map.put("activityReduction", preMoney + "");
        map.put("companyId", DataUtil.getInstance().getCompanyId());
        map.put("couponIds", couponIds);
        map.put("memberId", memberId);
        map.put("memberCardId", memberCardId);
        map.put("orderAmount", orderAmount);
        map.put("orderSource", "3");
        map.put("payAmount", payMent);
        map.put("payType", "4");
        map.put("productId", productId);
        map.put("productInfoId", productInfoId);
        map.put("terminalId", DataUtil.getInstance().getTerminalId());
        map.put("oilNum", oilNum);
        map.put("oilPrice", nowOilsPrice);
        map.put("serviceCardIds", serviceCardIds);
        map.put("couponIdsReceive", couponIdsReceive);
        map.put("storeId", DataUtil.getInstance().getStoreId());
        map.put("rebate", rebate);
        map.put("rebateAmount", rebateAmount + "");
        map.put("downAmount", downAmount + "");
        map.put("fullReductionAmount", fullReductionAmount);
        map.put("rise", rise);
        Log.d("xxxxx", map.toString());
        CreateOrder(context, map);
    }

    private void CreateOrder(Activity context, Map<String, String> map) {

        RequestUtils.CreateOrder(context, map, new MyObserver<CreateOrderBean>(context) {
            @Override
            public void onSuccess(CreateOrderBean bean) {
                getToken(context, token -> {
                    newToken=token;
                    getTokensBalancePay(context, token, bean.getPayAmount(), bean.getOrderNumber(), bean.getId());
                });
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                context.finish();
                ToastUtils.showToast(context.getApplicationContext(), errorMsg);
            }
        });
    }

    private void getTokensBalancePay(Activity context, String token, String payAmounts, String orderNumber, String orderNumberId) {
        if (StringUtils.isEmpty(paySwitch)) {
            ToastUtils.showToast(context.getApplicationContext(), "您的密码存在异常");
            return;
        }
        if ("0".equals(paySwitch)) {
            balancePay(context, "", payAmounts, orderNumberId, token, orderNumber);
        } else if ("1".equals(paySwitch)) {
            toPayData(context, payAmounts, orderNumber, token, orderNumberId);
        }
    }
    private String newToken="";

    private void balancePay(Activity context, String password, String payAmounts, String orderNumberId, String tokens, String orderNumber) {
        String psd = "";
        if ("0".equals(paySwitch)) {
            psd = "";
        } else if ("1".equals(paySwitch)) {
            psd = Md5Util.md5Hex(password);
        }
        Map<String, String> map = new HashMap<>();
        map.put("cardId", memberCardId);
        map.put("mainCardId", parentId);
        map.put("orderId", orderNumberId);
        map.put("payAmount", payAmounts);
        map.put("payPwd", psd);
        map.put("paySwitch", paySwitch);
        map.put("orderNumber", orderNumber);
        Log.d("xxTokenx",newToken+"=====");
        Log.d("xxTokenx",tokens+"=====");
        RequestUtils.BalancePay(context, map, newToken, new MyObserver<BaseBean>(context, false) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (code == ConfigureFile.code) {
                    if ("1".equals(DataUtil.getInstance().getMusicSwitch())) {
                        String amounts = AlgorithmUtil.getAmount(orderAmount, 100);
                        VoicePlay.with(context).play(amounts, false);
                    }
                    PayResultAc.start(context, orderNumber, "200", payAmounts, "1");
                    context.finish();
                }
                else if(code==203)
                {
                    payPassDialog.getPayViewPass().cleanAllTv();
                    getToken(context, token -> {
                        newToken=token;
                    });
                    ToastUtils.showToast(context.getApplicationContext(), errorMsg);
                }

                else {
                    context.finish();
                    ToastUtils.showToast(context.getApplicationContext(), errorMsg);
                }
            }
        });
    }

    private void toPayData(Activity context, String payAmounts, String orderNumber, String tokens, String orderNumberId) {
        if (payPassDialog == null) {
            payPassDialog = new PayPassDialog(context);
        }
        payPassDialog.getPayViewPass()
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        balancePay(context, passContent, payAmounts, orderNumberId, tokens, orderNumber);
                    }

                    @Override
                    public void onPayClose() {
                        updateOrderState(context, orderNumber);
                        payPassDialog.dismiss();
                    }

                    @Override
                    public void onPayForget() {

                    }
                });

    }

    private void updateOrderState(Context context, String orderNumber) {
        RequestUtils.CancelOrder(context, orderNumber, new MyObserver<BaseBean>(context) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {

            }
        });
    }

    static class PriceComparator implements Comparator {
        public int compare(Object object1, Object object2) {// 实现接口中的方法
            ConponYesList p1 = (ConponYesList) object1; // 强制转换
            ConponYesList p2 = (ConponYesList) object2;
            return new Double(p2.getPreAmount()).compareTo(new Double(p1.getPreAmount()));
        }
    }

}
